#!/bin/bash

# =============================================================================
# Dify 生产环境一键部署脚本 v1.1 (支持远程克隆)
# 支持 Ubuntu 20.04/22.04 LTS, CentOS 7/8, RHEL 7/8
# =============================================================================

set -euo pipefail
IFS=$'\n\t'

# --- 全局配置 ---
SCRIPT_VERSION="1.1.0"
DIFY_VERSION="0.6.13"
MIN_RAM_GB=4
MIN_DISK_GB=20
DEPLOY_USER="root"

# Gitee 仓库配置
GITEE_REPO="git@gitee.com:dd0129/dify_test.git"
DEPLOY_DIR="/root/dify"
DATA_DIR="/root/dify_data"  # 独立的数据目录，不会被清理

# --- 颜色输出 ---
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'
EMOJI_SUCCESS="✅"
EMOJI_ERROR="❌"
EMOJI_WARNING="⚠️"
EMOJI_INFO="ℹ️"

# --- 日志函数 ---
log_info() { echo -e "${BLUE}${EMOJI_INFO} [INFO]${NC} $1"; }
log_success() { echo -e "${GREEN}${EMOJI_SUCCESS} [SUCCESS]${NC} $1"; }
log_warning() { echo -e "${YELLOW}${EMOJI_WARNING} [WARNING]${NC} $1"; }
log_error() { echo -e "${RED}${EMOJI_ERROR} [ERROR]${NC} $1"; }

# --- 错误处理 ---
trap 'handle_error $LINENO' ERR
handle_error() {
    log_error "脚本在第 $1 行执行失败"
    log_error "请检查上面的错误信息并修复问题后重新运行"
    exit 1
}

# --- 系统检测函数 ---
detect_os() {
    if [[ -f /etc/os-release ]]; then
        source /etc/os-release
        OS=$ID
        VERSION=$VERSION_ID
    else
        log_error "无法检测操作系统类型"
        exit 1
    fi
    log_info "检测到操作系统: $OS $VERSION"
}

check_root() {
    if [[ $EUID -ne 0 ]]; then
        log_error "此脚本需要 root 权限运行"
        log_info "请使用: sudo bash $0"
        exit 1
    fi
}

check_system_requirements() {
    log_info "检查系统资源要求..."
    
    # 检查内存
    local ram_gb=$(free -g | awk '/^Mem:/{print $2}')
    if (( ram_gb < MIN_RAM_GB )); then
        log_error "内存不足，需要至少 ${MIN_RAM_GB}GB，当前: ${ram_gb}GB"
        exit 1
    fi
    
    # 检查磁盘空间
    local disk_gb=$(df -BG / | awk 'NR==2 {print $4}' | sed 's/G//')
    if (( disk_gb < MIN_DISK_GB )); then
        log_error "磁盘空间不足，需要至少 ${MIN_DISK_GB}GB，当前可用: ${disk_gb}GB"
        exit 1
    fi
    
    log_success "系统资源检查通过 (内存: ${ram_gb}GB, 磁盘: ${disk_gb}GB)"
}

# --- 系统更新 ---
update_system() {
    log_info "更新系统包..."
    
    case $OS in
        ubuntu|debian)
            export DEBIAN_FRONTEND=noninteractive
            
            # 更新软件包列表
            log_info "更新软件包列表..."
            apt-get update || {
                log_warning "软件包列表更新失败，继续执行..."
            }
            
            # 升级系统包
            log_info "升级系统包..."
            apt-get upgrade -y || {
                log_warning "系统包升级失败，继续执行..."
            }
            
            # 安装基础包
            log_info "安装基础系统包..."
            apt-get install -y curl wget gnupg lsb-release ca-certificates \
                software-properties-common apt-transport-https \
                net-tools git vim || {
                log_warning "某些基础包安装失败，继续执行..."
            }
            
            # 安装额外工具包（容错安装）
            log_info "安装额外工具包..."
            for package in ufw fail2ban htop iotop jq; do
                log_info "尝试安装 $package..."
                apt-get install -y "$package" || {
                    log_warning "$package 安装失败，跳过..."
                }
            done
            ;;
        centos|rhel|rocky|almalinux)
            # 配置CentOS 8 EOL仓库（如果需要）
            if [[ "$OS" == "centos" && "$VERSION" == "8" ]]; then
                log_info "配置CentOS 8 EOL仓库..."
                # 备份原有仓库配置
                mkdir -p /etc/yum.repos.d/backup
                cp /etc/yum.repos.d/CentOS-*.repo /etc/yum.repos.d/backup/ 2>/dev/null || true
                
                # 更新为vault仓库
                sed -i 's/mirrorlist/#mirrorlist/g' /etc/yum.repos.d/CentOS-*.repo 2>/dev/null || true
                sed -i 's|#baseurl=http://mirror.centos.org|baseurl=http://vault.centos.org|g' /etc/yum.repos.d/CentOS-*.repo 2>/dev/null || true
                
                # 清理缓存
                yum clean all 2>/dev/null || true
            fi
            
            # 更新系统包
            yum update -y
            
            # 安装基础包
            log_info "安装基础系统包..."
            yum install -y curl wget ca-certificates net-tools git vim || {
                log_warning "某些基础包安装失败，继续执行..."
            }
            
            # 配置EPEL仓库
            log_info "配置EPEL仓库..."
            if ! rpm -qa | grep -q epel-release; then
                yum install -y epel-release || {
                    log_warning "EPEL仓库安装失败，尝试直接下载安装..."
                    if [[ "$OS" == "centos" && "$VERSION" == "8" ]]; then
                        rpm -Uvh https://dl.fedoraproject.org/pub/epel/epel-release-latest-8.noarch.rpm 2>/dev/null || {
                            log_warning "EPEL仓库配置失败，部分工具可能不可用"
                        }
                    elif [[ "$OS" == "centos" && "$VERSION" == "7" ]]; then
                        rpm -Uvh https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm 2>/dev/null || {
                            log_warning "EPEL仓库配置失败，部分工具可能不可用"
                        }
                    fi
                }
            fi
            
            # 安装防火墙
            yum install -y firewalld || log_warning "firewalld安装失败"
            
            # 安装EPEL包（容错安装）
            log_info "安装额外工具包..."
            for package in gnupg2 fail2ban htop iotop jq; do
                log_info "尝试安装 $package..."
                yum install -y "$package" || {
                    log_warning "$package 安装失败，跳过..."
                    # 尝试替代包名
                    case "$package" in
                        gnupg2|gnupg)
                            yum install -y gnupg2 2>/dev/null || yum install -y gnupg 2>/dev/null || log_warning "gnupg相关包安装失败"
                            ;;
                        iotop)
                            yum install -y python3-iotop 2>/dev/null || log_warning "iotop替代包安装失败"
                            ;;
                    esac
                }
            done
            ;;
        *)
            log_error "不支持的操作系统: $OS"
            exit 1
            ;;
    esac
    
    log_success "系统更新完成"
}

# --- 验证SSH密钥配置 ---
verify_ssh_config() {
    log_info "验证root用户SSH配置..."
    
    if [[ ! -d "/root/.ssh" ]]; then
        log_warning "未找到SSH配置目录 /root/.ssh"
        log_info "请确保已配置SSH密钥以访问Gitee仓库"
    elif [[ ! -f "/root/.ssh/id_rsa" && ! -f "/root/.ssh/id_ed25519" ]]; then
        log_warning "未找到SSH私钥文件"
        log_info "请确保已配置SSH密钥以访问 $GITEE_REPO"
    else
        log_success "SSH配置目录存在"
    fi
}

# --- 安装 Docker ---
install_docker() {
    log_info "安装 Docker..."
    
    if command -v docker &> /dev/null; then
        log_warning "Docker 已安装，版本: $(docker --version)"
    else
        # 使用官方安装脚本
        curl -fsSL https://get.docker.com -o get-docker.sh
        sh get-docker.sh
        rm get-docker.sh
        
        # 启动服务
        systemctl enable docker
        systemctl start docker
        
        log_success "Docker 安装完成: $(docker --version)"
    fi
    
    # root用户无需添加到docker组
    log_info "使用root用户运行Docker，无需添加用户组"
}

# --- 配置 Docker 生产设置 ---
configure_docker() {
    log_info "配置 Docker 生产环境设置..."
    
    mkdir -p /etc/docker
    
    cat > /etc/docker/daemon.json << 'EOF'
{
  "registry-mirrors": [
    "https://docker.m.daocloud.io",
    "https://docker.1ms.run",
    "https://dytt.online",
    "https://registry.cyou"
  ],
  "log-driver": "json-file",
  "log-opts": {
    "max-size": "10m",
    "max-file": "3"
  },
  "storage-driver": "overlay2",
  "live-restore": true,
  "userland-proxy": false,
  "no-new-privileges": true,
  "default-ulimits": {
    "nofile": {
      "Name": "nofile",
      "Hard": 65536,
      "Soft": 65536
    }
  },
  "features": {
    "buildkit": true
  }
}
EOF
    
    systemctl restart docker
    log_success "Docker 生产配置完成"
}

# --- 配置防火墙 ---
configure_firewall() {
    log_info "配置防火墙..."
    
    case $OS in
        ubuntu|debian)
            # 配置 UFW
            ufw --force reset
            ufw default deny incoming
            ufw default allow outgoing
            ufw allow ssh
            ufw allow 80/tcp
            ufw allow 443/tcp
            ufw --force enable
            ;;
        centos|rhel|rocky|almalinux)
            # 配置 firewalld
            systemctl enable firewalld
            systemctl start firewalld
            firewall-cmd --permanent --add-service=ssh
            firewall-cmd --permanent --add-service=http
            firewall-cmd --permanent --add-service=https
            firewall-cmd --reload
            ;;
    esac
    
    log_success "防火墙配置完成"
}

# --- 从 Gitee 克隆项目 ---
clone_project() {
    log_info "从 Gitee 克隆项目..."
    
    # 智能目录管理：保护数据目录不被清理
    if [[ -d "$DEPLOY_DIR" ]]; then
        log_warning "检测到现有部署目录，准备智能清理并重新克隆..."
        
        # 检查是否有旧的数据目录在部署目录内
        if [[ -d "$DEPLOY_DIR/data" ]]; then
            log_info "检测到旧的数据目录在部署目录内，准备迁移数据..."
            
            # 创建独立数据目录
            mkdir -p "$DATA_DIR" || {
                log_error "创建独立数据目录失败"
                exit 1
            }
            
            # 迁移数据（如果独立数据目录不存在或为空）
            if [[ ! -d "$DATA_DIR/postgres" ]]; then
                log_info "迁移数据到独立数据目录: $DATA_DIR"
                cp -r "$DEPLOY_DIR/data"/* "$DATA_DIR/" 2>/dev/null || {
                    log_warning "数据迁移失败或无数据需要迁移"
                }
            else
                log_info "独立数据目录已存在，跳过数据迁移"
            fi
        fi
        
        # 安全删除部署目录（数据已迁移）
        log_info "删除部署目录: $DEPLOY_DIR"
        rm -rf "$DEPLOY_DIR" || {
            log_error "删除现有目录失败，请检查权限或文件占用情况"
            exit 1
        }
    fi
    
    # 重新创建部署目录
    log_info "创建部署目录: $DEPLOY_DIR"
    mkdir -p "$DEPLOY_DIR" || {
        log_error "创建部署目录失败"
        exit 1
    }
    
    # 进入部署目录
    cd "$DEPLOY_DIR" || {
        log_error "无法进入部署目录: $DEPLOY_DIR"
        exit 1
    }
    
    # 全新克隆项目
    log_info "克隆项目: $GITEE_REPO"
    git clone "$GITEE_REPO" . || {
        log_error "Git克隆失败，请检查网络连接和SSH密钥配置"
        log_error "请确保已配置root用户的SSH密钥以访问: $GITEE_REPO"
        exit 1
    }
    
    log_success "项目代码全新克隆完成（数据目录已保护）"
}

# --- 生成生产环境配置 ---
generate_production_configs() {
    log_info "生成生产环境配置文件..."
    
    local config_dir="$DEPLOY_DIR/config"
    mkdir -p "$config_dir"
    
    # 生成随机密钥
    local secret_key=$(openssl rand -base64 42)
    local db_password=$(openssl rand -base64 32 | tr -d '+/=' | cut -c1-24)
    local redis_password=$(openssl rand -base64 32 | tr -d '+/=' | cut -c1-24)
    
    # 生产环境变量
    cat > "$config_dir/.env.production" << EOF
# =============================================================================
# Dify 生产环境配置 (自动生成)
# =============================================================================

# 基础配置
EDITION=SELF_HOSTED
LOG_LEVEL=INFO
SECRET_KEY=$secret_key
MIGRATION_ENABLED=true

# 数据库配置
DB_USERNAME=dify
DB_PASSWORD=$db_password
DB_HOST=postgres
DB_PORT=5432
DB_DATABASE=dify

# Redis 配置
REDIS_HOST=redis
REDIS_PORT=6379
REDIS_PASSWORD=$redis_password
REDIS_USE_SSL=false

# Celery 配置
CELERY_BROKER_URL=redis://:$redis_password@redis:6379/1

# 存储配置
STORAGE_TYPE=local
STORAGE_LOCAL_PATH=/app/storage

# Session 配置
SESSION_TYPE=redis
SESSION_REDIS_HOST=redis
SESSION_REDIS_PORT=6379
SESSION_REDIS_PASSWORD=$redis_password

# 邮件配置 (禁用SMTP避免启动错误)
MAIL_TYPE=
MAIL_DEFAULT_SEND_FROM=noreply@your-domain.com
SMTP_SERVER=
SMTP_PORT=587
SMTP_USERNAME=
SMTP_PASSWORD=
SMTP_USE_TLS=true

# Web URLs (请替换为您的实际域名)
CONSOLE_WEB_URL=http://localhost
CONSOLE_API_URL=http://localhost
SERVICE_API_URL=http://localhost
APP_WEB_URL=http://localhost

# 代码执行配置
CODE_EXECUTION_ENDPOINT=http://sandbox:8194
CODE_EXECUTION_API_KEY=dify-sandbox
CODE_MAX_NUMBER=9223372036854775807
CODE_MIN_NUMBER=-9223372036854775808
CODE_MAX_DEPTH=5
CODE_MAX_PRECISION=20
CODE_MAX_STRING_LENGTH=80000
CODE_MAX_STRING_ARRAY_LENGTH=30
CODE_MAX_OBJECT_ARRAY_LENGTH=30
CODE_MAX_NUMBER_ARRAY_LENGTH=1000

# HTTP 代理配置
HTTP_PROXY=http://ssrf_proxy:3128
HTTPS_PROXY=http://ssrf_proxy:3128

# 监控配置
SENTRY_DSN=
SENTRY_TRACES_SAMPLE_RATE=1.0
SENTRY_PROFILES_SAMPLE_RATE=1.0

# 高级配置
DEBUG=false
API_DOCS_ENABLED=true
VECTOR_STORE=weaviate
WEAVIATE_ENDPOINT=http://weaviate:8080

# 通义千问配置 (已配置)
TONGYI_DASHSCOPE_API_KEY=sk-4ee0b71b1bbd4e48a5e46810278ccb14
EOF
    
    log_success "生产配置文件生成完成"
}

# --- 生成 Nginx 配置 ---
generate_nginx_config() {
    log_info "生成 Nginx 配置..."
    
    local nginx_dir="$DEPLOY_DIR/config/nginx"
    mkdir -p "$nginx_dir"
    
    # 复制生产配置文件，并调整为HTTP配置
    cp "$DEPLOY_DIR/nginx.production.conf" "$nginx_dir/nginx.conf"
    
    # 为测试环境调整配置 - 移除HTTPS重定向
    cat > "$nginx_dir/nginx.conf" << 'EOF'
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;

events {
    worker_connections 1024;
    use epoll;
    multi_accept on;
}

http {
    include /etc/nginx/mime.types;
    default_type application/octet-stream;

    log_format main '$remote_addr - $remote_user [$time_local] "$request" '
                    '$status $body_bytes_sent "$http_referer" '
                    '"$http_user_agent" "$http_x_forwarded_for"';

    access_log /var/log/nginx/access.log main;

    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    types_hash_max_size 2048;
    client_max_body_size 50M;

    gzip on;
    gzip_vary on;
    gzip_min_length 1000;
    gzip_proxied any;
    gzip_comp_level 6;
    gzip_types
        text/plain
        text/css
        text/xml
        text/javascript
        application/json
        application/javascript
        application/xml+rss
        application/atom+xml
        image/svg+xml;

    upstream api_backend {
        server api:5001;
        keepalive 32;
    }

    upstream web_backend {
        server web:3000;
        keepalive 32;
    }

    server {
        listen 80;
        server_name _;

        # API 路由
        location ~ ^/(api|console/api|v1|files) {
            proxy_pass http://api_backend;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Proto $scheme;
            
            proxy_connect_timeout 60s;
            proxy_send_timeout 60s;
            proxy_read_timeout 300s;
            
            proxy_http_version 1.1;
            proxy_set_header Connection "";
        }

        # Web 应用路由
        location / {
            proxy_pass http://web_backend;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Proto $scheme;
            
            proxy_connect_timeout 60s;
            proxy_send_timeout 60s;
            proxy_read_timeout 60s;
            
            proxy_http_version 1.1;
            proxy_set_header Connection "";
        }

        # 健康检查
        location /nginx-health {
            access_log off;
            return 200 "healthy\n";
            add_header Content-Type text/plain;
        }
    }
}
EOF
    
    log_success "Nginx 配置生成完成"
}

# --- 创建数据目录 ---
create_data_directories() {
    log_info "创建数据目录..."
    
    # 创建独立的数据目录（持久化，不会被清理）
    mkdir -p "$DATA_DIR"/{postgres,redis,weaviate,uploads}
    
    # 创建部署目录下的非数据目录
    mkdir -p "$DEPLOY_DIR"/{logs,backups,config/ssl}
    mkdir -p "$DEPLOY_DIR"/logs/nginx
    
    log_info "设置数据目录权限以支持Docker容器..."
    
    # 设置PostgreSQL数据目录权限 (UID 999)
    chown -R 999:999 "$DATA_DIR"/postgres
    chmod -R 750 "$DATA_DIR"/postgres
    
    # 设置Redis数据目录权限 (UID 999)
    chown -R 999:999 "$DATA_DIR"/redis
    chmod -R 750 "$DATA_DIR"/redis
    
    # 设置Weaviate数据目录权限 (UID 1000)
    chown -R 1000:1000 "$DATA_DIR"/weaviate
    chmod -R 755 "$DATA_DIR"/weaviate
    
    # 设置上传目录权限 (UID 1001，API服务需要写入)
    chown -R 1001:1001 "$DATA_DIR"/uploads
    chmod -R 755 "$DATA_DIR"/uploads
    
    # 设置其他目录权限 (root用户)
    chown -R root:root "$DEPLOY_DIR"/{logs,backups,config}
    chmod -R 755 "$DEPLOY_DIR"/{logs,backups,config}
    
    log_success "数据目录权限配置完成"
    log_info "数据目录位置: $DATA_DIR (持久化，不会被清理)"
    log_info "日志和配置目录: $DEPLOY_DIR (随代码更新)"
}

# --- 配置系统服务 ---
configure_system_service() {
    log_info "配置系统服务..."
    
    # 复制维护脚本
    cp "$DEPLOY_DIR/maintenance.sh" /usr/local/bin/dify-maintenance
    chmod +x /usr/local/bin/dify-maintenance
    
    cat > /etc/systemd/system/dify.service << EOF
[Unit]
Description=Dify Production Service
Requires=docker.service
After=docker.service

[Service]
Type=oneshot
RemainAfterExit=yes
ExecStart=/bin/bash -c 'cd $DEPLOY_DIR && docker compose -f docker-compose.production.yml up -d'
ExecStop=/bin/bash -c 'cd $DEPLOY_DIR && docker compose -f docker-compose.production.yml down'
TimeoutStartSec=300
User=root
Group=root

[Install]
WantedBy=multi-user.target
EOF
    
    systemctl daemon-reload
    systemctl enable dify
    
    log_success "系统服务配置完成"
}

# --- 启动服务 ---
start_services() {
    log_info "启动 Dify 服务..."
    
    cd "$DEPLOY_DIR"
    
    # 拉取镜像
    docker compose -f docker-compose.production.yml pull
    
    # 启动服务
    systemctl start dify
    
    # 等待服务启动
    sleep 30
    
    # 检查服务状态
    docker compose -f docker-compose.production.yml ps
    
    log_success "Dify 服务启动完成"
}

# --- 验证部署 ---
verify_deployment() {
    log_info "验证部署状态..."
    
    cd "$DEPLOY_DIR"
    
    # 检查容器状态
    local running_containers=$(docker compose -f docker-compose.production.yml ps --format json | jq -r '. | select(.State == "running") | .Service' | wc -l)
    local total_containers=$(docker compose -f docker-compose.production.yml ps --format json | jq -r '.Service' | wc -l)
    
    echo ""
    echo "=== 部署验证结果 ==="
    echo "运行中的容器: $running_containers/$total_containers"
    
    # 测试Web访问
    sleep 10
    if curl -f http://localhost > /dev/null 2>&1; then
        log_success "Web服务访问正常: http://localhost"
    else
        log_warning "Web服务可能还在启动中，请稍候再试"
    fi
    
    # 测试API访问
    if curl -f http://localhost/console/api/setup > /dev/null 2>&1; then
        log_success "API服务访问正常: http://localhost/console/api/setup"
    else
        log_warning "API服务可能还在启动中，请稍候再试"
    fi
    
    echo ""
    echo "=== 服务状态 ==="
    docker compose -f docker-compose.production.yml ps
}

# --- 生成部署报告 ---
generate_deployment_report() {
    log_info "生成部署报告..."
    
    local report_file="$DEPLOY_DIR/deployment-report-$(date +%Y%m%d_%H%M%S).txt"
    
    cat > "$report_file" << EOF
================================================================================
Dify 生产环境部署报告 (从Gitee远程部署)
================================================================================

部署时间: $(date)
脚本版本: $SCRIPT_VERSION
Dify 版本: $DIFY_VERSION
操作系统: $OS $VERSION
部署目录: $DEPLOY_DIR
仓库地址: $GITEE_REPO

服务状态:
$(cd "$DEPLOY_DIR" && docker compose -f docker-compose.production.yml ps)

系统资源:
CPU: $(nproc) 核
内存: $(free -h | grep '^Mem:' | awk '{print $2}')
磁盘: $(df -h / | tail -1 | awk '{print $2}')

访问地址:
- Web界面: http://localhost
- API接口: http://localhost/console/api
- 健康检查: http://localhost/nginx-health

管理命令:
- 启动服务: systemctl start dify
- 停止服务: systemctl stop dify
- 重启服务: systemctl restart dify
- 查看状态: systemctl status dify
- 维护工具: dify-maintenance help

配置文件:
- 环境配置: $DEPLOY_DIR/config/.env.production
- Nginx配置: $DEPLOY_DIR/config/nginx/nginx.conf
- Docker配置: $DEPLOY_DIR/docker-compose.production.yml

数据目录:
- 数据库: $DEPLOY_DIR/data/postgres
- 缓存: $DEPLOY_DIR/data/redis
- 向量库: $DEPLOY_DIR/data/weaviate
- 上传文件: $DEPLOY_DIR/data/uploads
- 日志: $DEPLOY_DIR/logs
- 备份: $DEPLOY_DIR/backups

下一步操作:
1. 访问 http://localhost 验证部署
2. 如需HTTPS，配置SSL证书
3. 根据需要修改 $DEPLOY_DIR/config/.env.production
4. 使用 dify-maintenance 命令管理服务

================================================================================
EOF
    
    chown root:root "$report_file"
    chmod 644 "$report_file"
    log_success "部署报告已生成: $report_file"
}

# --- 主函数 ---
main() {
    echo "==============================================================================="
    echo "🚀 Dify 生产环境一键部署脚本 v$SCRIPT_VERSION (支持Gitee远程克隆)"
    echo "==============================================================================="
    echo ""
    
    # 系统检查
    check_root
    detect_os
    check_system_requirements
    
    echo ""
    log_info "开始从 Gitee 部署 Dify 生产环境..."
    echo ""
    
    # 执行部署步骤
    update_system
    verify_ssh_config
    install_docker
    configure_docker
    configure_firewall
    
    # 克隆项目和生成配置
    clone_project
    generate_production_configs
    generate_nginx_config
    create_data_directories
    
    # 启动和验证
    configure_system_service
    start_services
    verify_deployment
    
    # 生成报告
    generate_deployment_report
    
    echo ""
    echo "==============================================================================="
    log_success "🎉 Dify 生产环境部署完成！"
    echo "==============================================================================="
    echo ""
    log_info "📋 访问信息："
    echo "   🌐 Web界面: http://localhost"
    echo "   🔧 API接口: http://localhost/console/api"
    echo "   ❤️  健康检查: http://localhost/nginx-health"
    echo ""
    log_info "📋 管理命令："
    echo "   systemctl start|stop|restart|status dify"
    echo "   dify-maintenance help"
    echo ""
    log_info "📁 重要目录："
    echo "   项目目录: $DEPLOY_DIR"
    echo "   配置文件: $DEPLOY_DIR/config/.env.production"
    echo "   数据目录: $DEPLOY_DIR/data/"
    echo "   日志目录: $DEPLOY_DIR/logs/"
    echo ""
    log_info "📖 详细信息请查看部署报告"
    echo ""
}

# 运行主函数
main "$@" 